package com.itheima.health.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.security.SecurityContext;
import com.itheima.health.security.SecurityUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//拦截所有
@WebFilter("/*")
@Slf4j
public class SecurityFilter implements Filter {
    private AntPathMatcher antPathMatcher=new AntPathMatcher();
    //不需要拦截可以直接访问的路径数组
    private String[] notNeedFilterPaths={
            "/user/login",
            "/user/logout",
            "/common/**",
            "/mobile/**",
            "/checkitem/**",
            "/**",
            "/setmeal/getSetmeal"
    };
    //存放用户登录后,访问的URL和所需的权限
    //private Map<String,String> needPermissionUrl=new HashMap<>();

   /* @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        needPermissionUrl.put("/checkgroup/add","CHECKGROUP_ADD");
        needPermissionUrl.put("/checkgroup/findPage","CHECKGROUP_QUERY");
        needPermissionUrl.put("/checkgroup/findById","CHECKGROUP_QUERY");
        needPermissionUrl.put("/checkgroup/findCheckItemIdsByCheckGroupId","CHECKGROUP_QUERY");
        needPermissionUrl.put("/checkgroup/edit","CHECKGROUP_EDIT");
        needPermissionUrl.put("/checkgroup/findAll","CHECKGROUP_QUERY");
        needPermissionUrl.put("/checkgroup/deleteCheckGroupitemById","CHECKGROUP_DELETE");

        needPermissionUrl.put("/checkitem/add","CHECKITEM_ADD");
        needPermissionUrl.put("/checkitem/findPage","CHECKITEM_QUERY");
        needPermissionUrl.put("/checkitem/delete","CHECKITEM_DELETE");
        needPermissionUrl.put("/checkitem/edit","CHECKITEM_EDIT");
        needPermissionUrl.put("/checkitem/findById","CHECKITEM_QUERY");
        needPermissionUrl.put("/checkitem/findAll","CHECKITEM_QUERY");

        needPermissionUrl.put("/setmeal/upload","SETMEAL_ADD");
        needPermissionUrl.put("/setmeal/add","SETMEAL_ADD");
        needPermissionUrl.put("/setmeal/findPage","SETMEAL_QUERY");
        needPermissionUrl.put("/setmeal/getSetmeal","SETMEAL_QUERY");

        needPermissionUrl.put("/report/**","REPORT_VIEW");



    }*/

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //获取当前请求的路径
        String requestURI = req.getRequestURI();
        log.info("[登陆判断]正在执行,当前请求路径为:{}",requestURI);
        if (needSecurity(requestURI)) {
            //需要登陆才能访问
            //判断是否已经登陆过
            SecurityUser securityUser = (SecurityUser) req.getSession().getAttribute(MessageConst.CURRENT_USER);
            if (securityUser==null) {
                //如果没有登陆,跳转登陆界面
                log.info("[登陆判断]-用户未登录,跳转登陆界面");
                resp.setContentType("application/json;charset=UTF-8");
                resp.getWriter().write(JSON.toJSONString(new Result(false, "请重新登录")));
                return;
            }else {
                //已经登陆过了
                log.info("[登陆判断]-保存当前用户:{}",securityUser.getUsername());
                SecurityContext.setSecurityUserThreadLocal(securityUser);
                /*log.info("[权限过滤器]-用户已登录-进行权限检查");
                //判断该用户是否有权限访问该URl
                if (checkSecurityUserPermission(requestURI,securityUser)){
                    //有权限,放行
                    log.info("[权限过滤器]-权限检查结果-通过");
                    filterChain.doFilter(req,resp);
                }else {
                    //没有权限,返回"没有操作权限"信息
                    log.info("[权限过滤器]-权限检查结果-未通过,禁止访问");
                    resp.setContentType("application/json; charset=UTF-8");
                    resp.getWriter().write(JSON.toJSONString(new Result(false, "没有操作权限")));
                }*/
            }
        }else {
            log.info("[登陆判断]-通过");
            //不需要登陆就可以访问
            //放行
            filterChain.doFilter(req,resp);
            //SecurityContext.removeSecurityUserThreadLocal();
        }
    }

    /*private boolean checkSecurityUserPermission(String requestURI, SecurityUser securityUser) {
        //needPermissionUrl///requestURI.equals(url)
        //根据key匹配requestURI,
        Set<String> urls = needPermissionUrl.keySet();
        for (String url : urls) {
            if (antPathMatcher.match(url,requestURI)) {
                //匹配到,
                //进行权限匹配
                String needPermission = needPermissionUrl.get(url);
                log.info("[权限过滤器]-正在对用户:{}访问路径:{}进行权限检查",securityUser.getUsername(),requestURI);
                Set<Role> roles = securityUser.getRoles();
                for (Role role : roles) {
                    Set<Permission> userPermissions = role.getPermissions();
                    for (Permission userPermission : userPermissions) {
                        if (userPermission.getKeyword().equals(needPermission)) {
                            return true;
                        }
                    }
                    //该角色没有权限
                    return false;
                }
            }
        }
        //没有匹配到url,可以访问
        log.info("[权限过滤器]-当前URL:{}无需权限,可以访问",requestURI);
        return true;

    }*/

    //判断访问该路径是否需要登陆
    private boolean needSecurity(String requestURI){
        for (String notNeedFilterPath : notNeedFilterPaths) {
            if (antPathMatcher.match(notNeedFilterPath,requestURI)) {
                //不需要拦截
                return false;
            }
        }
        //不包含,需要拦截
        return true;
    }

}
